package com.gcloud.core.messagebus;

import com.gcloud.core.util.MessageUtil;
import com.gcloud.header.GMessage;
import com.gcloud.header.NeedReplyMessage;
import com.gcloud.header.ReplyMessage;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
Copyright (c) [2020] [G-CLOUD TECHNOLOGY] [G-Cloud 8.0] is licensed under the Mulan PSL v1.
You can use this software according to the terms and conditions of the Mulan PSL v1. You may obtain
a copy of Mulan PSL v1 at: http://license.coscl.org.cn/MulanPSL THIS SOFTWARE IS PROVIDED ON AN 
"AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. See the Mulan PSL v1 for more details.
 */

@Service
public class MessageBusImpl implements MessageBus{
	@Autowired
    private AmqpTemplate rabbitTemplate;
	
	@Override
	public <REQ extends GMessage> void send(REQ msg) {
		// TODO Auto-generated method stub
		rabbitTemplate.convertAndSend(msg.getServiceId() + "_async", msg);
	}
	
	@Override
	public <RPLY extends ReplyMessage> RPLY call(NeedReplyMessage msg, Class<RPLY> clazz) {
		// TODO Auto-generated method stub
		Object obj = rabbitTemplate.convertSendAndReceive(msg.getServiceId(),msg);
		return clazz.cast(MessageUtil.fromMessage(obj));
	}

	@Override
	public ReplyMessage call(NeedReplyMessage msg) {
		return call(msg, msg.replyClazz());
	}
}